import axios from "axios";
import qs from "qs";
// md5加密库
import CryptoJS from "crypto-js";
// import params from "./dev.js"
import params from "./prod.js";
import { Toast } from "vant";

const VIDEO_BASE_URL = "https://a1.easemob.com";

const whileList = [
  VIDEO_BASE_URL,
  "api.php",
  "https://a1.easemob.com",
  "get-policy"
];
const inWhiteList = url => whileList.some(item => url.includes(item));
const needParamsURL = "/api/open/wujing/";

//设置请求头
axios.interceptors.request.use(
  config => {
    // config = setToken(config)
    console.log(config, "config");
    if (config.url.includes(needParamsURL)) config = setParams(config);

    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

const successCode = [10000, 1, 200];
// 添加响应拦截器
axios.interceptors.response.use(
  response => {
    if (inWhiteList(response.config.url)) return response;

    if (successCode.includes(response.data.code)) return response.data;
    else {
      Toast(response.data.msg);
      return Promise.reject(new Error(response.data.msg || "Error"));
    }
  },
  error => {
    Toast(error.message);
    return Promise.reject(error);
  }
);

const setToken = config => {
  let token = localStorage.getItem("token");
  if (token) {
    // 判断是否存在token，如果存在的话，则每个http header都加上token
    config.headers.Authorization = token;
    // console.log('interceptors config=', config)
  }
  return config;
};

const setParams = config => {
  // 获取当前10位的时间戳
  const timestamp = Math.round(new Date().getTime() / 1000).toString();
  // secret + 10位时间戳的前六位，然后进行两次MD5加密
  const sign = CryptoJS.MD5(
    CryptoJS.MD5(params.secret + timestamp.slice(0, 6)).toString()
  ).toString();

  //2021-04-25 所有请求新增四个必传参数

  if (config.method == "post") {
    let data = qs.parse(config.data);
    config.data = qs.stringify({
      timestamp: timestamp,
      from: params.from,
      sign: sign,
      companyId: params.companyId,
      ...data
    });
  } else {
    let data = config.params;
    config.params = {
      timestamp: timestamp,
      from: params.from,
      sign: sign,
      companyId: params.companyId,
      ...data
    };
  }

  return config;
};

export default axios;
